package org.dromara.web.plugins.aliasr;


import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.nls.client.AccessToken;
import okhttp3.*;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.Date;

@Component
public class AliAsrService implements InitializingBean {

    public static final String url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";
    public static final String appKey = "gBpUyubTIS2usjcG";
    public static final String REQUEST_URL = url + "?appkey=" + appKey + "&format=mp3&sample_rate=16000&enable_punctuation_prediction=true&enable_inverse_text_normalization=true&enable_voice_detection=true";

    public static final String TEXT_TO_VOICE_URL = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey="+ appKey + "&format=wav&sample_rate=16000&text=";

    public static final String ACCESS_KEY_ID = "LTAI5tLtcajKSnLV73Kb8381";
    public static final String ACCESS_KEY_SECRET = "fk7L9PvRfsvVaoVrKT7HZOV2CEy9YJ";

    @Autowired
    OkHttpClient okHttpClient;


    private String token;
    private long expireTimestamp= 0L;


    @Override
    public void afterPropertiesSet() throws Exception {
        this.getAccessToken();
    }

    public String voiceToText(byte[] bytes) {

        this.checkToken();

        MediaType mediaType = MediaType.parse("application/octet-stream"); // 根据实际情况选择合适的媒体类型
        RequestBody requestBody = RequestBody.create(mediaType, bytes);

        Request request = new Request.Builder()
            .url(REQUEST_URL)
            .header("X-NLS-Token", token)
            .post(requestBody)
            .build();


        try {
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new ServiceException("服务异常");
            } else {
                String body = response.body().string();
                return body;
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("服务异常");
        }
    }


    public byte[] textToVoice(String text) {
        this.checkToken();


        Request request = new Request.Builder()
            .url(TEXT_TO_VOICE_URL + URLEncodeUtil.encode(text))
            .header("X-NLS-Token", token)
            .get()
            .build();


        try {
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new ServiceException("服务异常");
            } else {
                return response.body().bytes();
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("服务异常");
        }

    }


    private void checkToken() {
        if (new Date().getTime() / 1000 > expireTimestamp - 300) {
            this.getAccessToken();
        }
    }


    public void getAccessToken() {
        AccessToken accessToken = new AccessToken(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            accessToken.apply();
            token = accessToken.getToken();
            expireTimestamp = accessToken.getExpireTime();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
